/**
 * 
 */
package com.android.weibogo;

import com.android.weibogo.WeibogoData.Accounts;
import com.android.weibogo.WeibogoData.WeiboAccounts;

import com.android.weibogo.R;
import android.content.ComponentName;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.RelativeLayout;

import android.app.ListActivity;

/**
 * @author xiang.jianhua
 *
 */
public class WeibogoAccounts extends ListActivity {
	/* (non-Javadoc)
	 * @see android.app.Activity#onPause()
	 */
	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
	}

	/* (non-Javadoc)
	 * @see android.app.Activity#onResume()
	 */
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
	}

	/* (non-Javadoc)
	 * @see android.app.Activity#onStart()
	 */
	@Override
	protected void onStart() {
		// TODO Auto-generated method stub
		super.onStart();
	}

	/* (non-Javadoc)
	 * @see android.app.Activity#onStop()
	 */
	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		super.onStop();
	}

	private static final String TAG = "WeibogoAccounts";
    // Menu item ids
    public static final int MENU_ACCOUNT_DEL = Menu.FIRST;
    public static final int MENU_ACCOUNT_ADD = Menu.FIRST + 1;
    /**
     * The columns we are interested in from the database
     */
    private static final String[] PROJECTION = new String[] {
    		Accounts._ID, // 0
    		Accounts.NAME, // 1
    		Accounts.SEX, //2
    		Accounts.EMAIL, //3
    		Accounts.IS_DEFAULT_USER //4
    };
    /** The index of the title column */
    private static final int COLUMN_INDEX_TITLE = 1;
    
    private AccountsSimpleCursorAdapter mAdapter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setDefaultKeyMode(DEFAULT_KEYS_SHORTCUT);
        setContentView(R.layout.accounts_list);
        RelativeLayout layout = (RelativeLayout)findViewById(R.id.Accounts_relativeLayout);
        layout.setBackgroundResource(R.drawable.background);
        // Inform the list we provide context menus for items
        getListView().setOnCreateContextMenuListener(this);
        // Perform a managed query. The Activity will handle closing and requerying the cursor
        // when needed.
        Cursor cursor = managedQuery(getIntent().getData(), PROJECTION, null, null,
        		WeibogoData.DEFAULT_SORT_ORDER);
        // Used to map notes entries from the database to views
        mAdapter = new AccountsSimpleCursorAdapter(this, R.layout.account_item, cursor,
                new String[] { Accounts.NAME, Accounts.EMAIL }, 
                new int[] { R.id.account_name, R.id.account_email});
        setListAdapter(mAdapter);
        
    	if(cursor == null || cursor.getCount() <= 0){
        	//new user account
        	Intent intent = new Intent(this, WeibogoAddAccount.class);
        	intent.setData(Accounts.CONTENT_URI);
        	startActivity(intent);
    	}
    }
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);

        // This is our one standard application action -- inserting a
        // new note into the list.
        menu.add(0, MENU_ACCOUNT_ADD, 0, R.string.menu_account_add)
                .setShortcut('3', 'a')
                .setIcon(android.R.drawable.ic_menu_add);

        // Generate any additional actions that can be performed on the
        // overall list.  In a normal install, there are no additional
        // actions found here, but this allows other applications to extend
        // our menu with their own actions.
        Intent intent = new Intent(null, getIntent().getData());
        intent.addCategory(Intent.CATEGORY_ALTERNATIVE);
        menu.addIntentOptions(Menu.CATEGORY_ALTERNATIVE, 0, 0,
                new ComponentName(this, WeibogoAccounts.class), null, intent, 0, null);

        return true;
    }
    
    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        super.onPrepareOptionsMenu(menu);
        final boolean haveItems = getListAdapter().getCount() > 0;

        // If there are any notes in the list (which implies that one of
        // them is selected), then we need to generate the actions that
        // can be performed on the current selection.  This will be a combination
        // of our own specific actions along with any extensions that can be
        // found.
        if (haveItems) {
            // This is the selected item.
            Uri uri = ContentUris.withAppendedId(getIntent().getData(), getSelectedItemId());

            // Build menu...  always starts with the EDIT action...
            Intent[] specifics = new Intent[1];
            specifics[0] = new Intent(Intent.ACTION_EDIT, uri);
            MenuItem[] items = new MenuItem[1];

            // ... is followed by whatever other actions are available...
            Intent intent = new Intent(null, uri);
            intent.addCategory(Intent.CATEGORY_ALTERNATIVE);
            menu.addIntentOptions(Menu.CATEGORY_ALTERNATIVE, 0, 0, null, specifics, intent, 0,
                    items);

            // Give a shortcut to the edit action.
            if (items[0] != null) {
                items[0].setShortcut('1', 'e');
            }
        } else {
            menu.removeGroup(Menu.CATEGORY_ALTERNATIVE);
        }

        return true;
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case MENU_ACCOUNT_ADD:
            // Launch activity to insert a new item
            startActivityForResult(new Intent(Intent.ACTION_INSERT, getIntent().getData()), 1);
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
    
    /* (non-Javadoc)
	 * @see android.app.Activity#onActivityResult(int, int, android.content.Intent)
	 */
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		switch (resultCode) {
		case RESULT_OK:
			//notify data changed
			mAdapter.notifyDataSetChanged();
			break;

		default:
			break;
		}
	}

	@Override
    public void onCreateContextMenu(ContextMenu menu, View view, ContextMenuInfo menuInfo) {
        AdapterView.AdapterContextMenuInfo info;
        try {
             info = (AdapterView.AdapterContextMenuInfo) menuInfo;
        } catch (ClassCastException e) {
            Log.e(TAG, "bad menuInfo", e);
            return;
        }

        Cursor cursor = (Cursor) getListAdapter().getItem(info.position);
        if (cursor == null) {
            // For some reason the requested item isn't available, do nothing
            return;
        }

        // Setup the menu header
        menu.setHeaderTitle(cursor.getString(COLUMN_INDEX_TITLE));

        // Add a menu item to delete the note
        menu.add(0, MENU_ACCOUNT_DEL, 0, R.string.menu_account_del);
    }

    @Override
    public boolean onContextItemSelected(MenuItem item) {
        AdapterView.AdapterContextMenuInfo info;
        try {
             info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
        } catch (ClassCastException e) {
            Log.e(TAG, "bad menuInfo", e);
            return false;
        }

        switch (item.getItemId()) {
            case MENU_ACCOUNT_DEL: {
                // Delete the note that the context menu is for
                Uri accountUri = ContentUris.withAppendedId(getIntent().getData(), info.id);
                getContentResolver().delete(accountUri, null, null);
                return true;
            }
        }
        return false;
    }
    
    @Override
    protected void onListItemClick(ListView l, View v, int position, long id) {
		String selection = Accounts.IS_DEFAULT_USER + " ='" + WeibogoData.YES + "'";
		//remove the default user flag
		ContentValues values = new ContentValues();
		values.put(Accounts.IS_DEFAULT_USER, WeibogoData.NO);
		getContentResolver().update(Accounts.CONTENT_URI, values, selection, null);
		//set the new default user flag
		Uri tmpUri = ContentUris.withAppendedId(
				Accounts.CONTENT_URI, id);
		values.put(Accounts.IS_DEFAULT_USER, WeibogoData.YES);
		getContentResolver().update(tmpUri, values, null, null);
		
    	 // Launch activity to view/edit the currently selected item
    	 Intent intent = new Intent(this, WeiboSelector.class);
    	 intent.setData(WeiboAccounts.CONTENT_URI);
    	 intent.putExtra("weibogoAccountId", Long.toString(id));
    	 intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
         startActivity(intent);
    }
}
